<template>
  <div class="xtx-numbox">
    <div class="label" v-if="showLabel">数量</div>
    <div class="numbox">
      <a href="javascript:;" @click="toggle(-1)">-</a>
      <input type="text" :value="modelValue" @change="onChange" />
      <a href="javascript:;" @click="toggle(+1)">+</a>
    </div>
  </div>
</template>

<script lang="ts" setup name="XtxNumbox">
import { ComponentInternalInstance, getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const props = defineProps({
  modelValue: {
    type: Number,
    default: 0
  },
  min: {
    type: Number,
    default: 0
  },
  max: {
    type: Number,
    default: 20
  },
  showLabel: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits<{
  (e: 'update:modelValue', val: number): void
}>()
const onChange = (e: Event) => {
  let el = e.target as HTMLInputElement
  let newValue = +el.value
  if (isNaN(newValue)) {
    newValue = 0
  }
  if (newValue < props.min) {
    newValue = props.min
  } else if (newValue > props.max) {
    newValue = props.max
  }
  emit('update:modelValue', newValue)
  // 强制刷新页面,解决输入框不更新的问题
  proxy?.$forceUpdate()
}
const toggle = (val: number) => {
  let newValue = props.modelValue + val
  if (newValue < props.min) {
    newValue = props.min
  } else if (newValue > props.max) {
    newValue = props.max
  }
  emit('update:modelValue', newValue)
}
</script>

<style scoped lang="less">
.xtx-numbox {
  display: flex;
  align-items: center;
  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }
  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;
    > a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;
      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }
      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }
    > input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>
